package work.huangxin.share.controller.classSchedule;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import work.huangxin.share.domain.other.UserMessage;
import work.huangxin.share.domain.other.WXSessionModel;
import work.huangxin.share.domain.schedule.ClassSecheduleVO;
import work.huangxin.share.domain.schedule.NoteInfo;
import work.huangxin.share.service.ClassScheduleService;
import work.huangxin.share.service.NoteInfoService;
import work.huangxin.share.service.impl.UserMessageOperationService;
import work.huangxin.share.util.status.BaseResponse;
import work.huangxin.share.util.status.CodeEnum;
import work.huangxin.share.util.status.ResponseData;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;

/**
 * @author 季台星
 * @Date 2023 04 24 12 40
 */
@RestController
@RequestMapping("/wx/note")
public class NoteInfoController {
    @Autowired
    private NoteInfoService noteInfoService;
    @Autowired
    private ClassScheduleService classScheduleService;
    @Autowired
    private UserMessageOperationService userMessageOperationService;

    @GetMapping("/getNote")
    public BaseResponse getNoteInfoByUserId(HttpServletRequest request) {
        WXSessionModel user = (WXSessionModel) request.getSession().getAttribute("user");
        Integer userId = user.getUserId();
        List<NoteInfo> noteInfos = noteInfoService.getNoteInfoByUserId(Long.valueOf(userId));
        if (Objects.isNull(noteInfos)) {
            return ResponseData.error(CodeEnum.NOT_FOUND);
        }
        return ResponseData.success(noteInfos);
    }

    @PostMapping("/addNote")
    public BaseResponse saveNoteInfo(@RequestBody ClassSecheduleVO classSecheduleVO) {
        //必须要有scheduleId,userId
        UserMessage userMessage =
                userMessageOperationService.getUserMessage(
                        Math.toIntExact(classSecheduleVO.getNoteInfo().getUserId()));
        classSecheduleVO.setClazzName(userMessage.getClazzName());
        if (classSecheduleVO.getId() != null) {
            NoteInfo noteInfo = new NoteInfo();
            BeanUtils.copyProperties(classSecheduleVO.getNoteInfo(), noteInfo);
            noteInfo.setScheduleId(classSecheduleVO.getId());
            noteInfoService.saveNoteInfo(noteInfo);
        } else {
            Long scheduleId = classScheduleService.insertWithUserId(classSecheduleVO);
            noteInfoService.saveNoteInfoWithScheduleId(classSecheduleVO, scheduleId);
        }
        return ResponseData.success();
    }
}
